import querystring from "querystring";
import settings from "@/settings";
import { getEnterpriseId } from "@/utils/getEnterpriseId";
import UrlFactory from "./urlFactory.js";

// export const getAuthen = function () {
//   const search = window.location.search
//  /**
//  * 这一段作用是先跳转网页后再跳转
//  **/
//   if (search !== '') {
//     const search = querystring.parse(window.location.search.replace("?", ''))
//     let appIdPromise
//     // 有enterpriseId
//     if (!!search.enterpriseId) {
//       $nuxt.$store.commit("authen/setEnterpriseId", search.enterpriseId)
//     } else {
//       alert('你没有传递站点参数');
//     }

//     if (!!search.appId) {
//       // 从腾讯回来，有appId
//       $nuxt.$store.commit("authen/setAppId", search.appId)
//       appIdPromise = Promise.resolve();
//     } else {
//       // 第一次进入，只有stationid，没有appId，要数据库里拉取appid
//       // appIdPromise = $nuxt.$store.dispatch('authen/getAppId', search.enterpriseId).then((res) => {
//       //   $nuxt.$store.commit("authen/setEnterpriseId", res.enterpriseId)
//       // })
//       appIdPromise = $nuxt.$store.dispatch('authen/getAppId', search.enterpriseId)
//     }

//     // 拿到当前地址 此时页面还没跳转
//     const path = window.location.pathname === "/authen" ? "/" : window.location.pathname
//     // 替换为自己的标识符号
//     const searchStr = window.location.search.replace("?", ".").replace(/&/g, "-").replace(/=/g, "_")

//     appIdPromise.then(() => {
//       window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + $nuxt.$store.getters["authen/appId"] + "&redirect_uri=" + settings.baseUrl + "%2fauthen&response_type=code&scope=snsapi_base&state=" + path + searchStr + "#wechat_redirect"
//     })
//   } else {
//     alert("请传递站点参数")
//   }
// }

/**
 * 这一段作用是先跳转网页后再跳转
 * 老系统认证专用
 **/
// export const getAuthen = function () {
//   const enterpriseId = getEnterpriseId();
//   if(!enterpriseId){
//     alert("请传递站点参数")
//     return
//   }

//   const path = window.location.pathname === "/authen" ? ("/" + enterpriseId) : window.location.pathname
//   console.log('path',path)
//   const searchStr = window.location.search.replace("?", ".").replace(/&/g, "-").replace(/=/g, "_")
//   console.log('searchStr',searchStr);

//   $nuxt.$store.dispatch('authen/getAppId', enterpriseId).then(()=>{
//     sessionStorage.setItem('enterpriseId', enterpriseId)
//     window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + $nuxt.$store.getters["authen/appId"] + "&redirect_uri=" + settings.baseUrl + "authen&response_type=code&scope=snsapi_base&state=" + path + searchStr + "#wechat_redirect"
//   })
// }
/**
 * 这一段作用是先跳转网页后再跳转
 * 新的获取手机号
 **/
export const getAuthen = async (goUrl, key) => {
  try {
    console.log("进入getAuthen 方法");
    console.log('手机号为--'+$nuxt.$store.state["authen/phoneOrigin"]);
    const enterpriseId = getEnterpriseId();
    const urlProcessor = UrlFactory.getInstance();

    console.log('1111---getAuthen页面的enterpriseId',enterpriseId)
    if (!enterpriseId) {
      alert("请传递站点参数");
      return;
    }

    // const path = window.location.pathname === "/authen" ? ("/" + enterpriseId) : window.location.pathname
    // const searchStr = window.location.search.replace("?", ".").replace(/&/g, "-").replace(/=/g, "_")
    // const originUrl = path + searchStr;
    const originUrl = !!goUrl ? goUrl : urlProcessor.encodeUrlStr();

    // 获取油企信息----这里不需要做数据的存储吗
    const enterpriseInfo = await $nuxt.$axios.$get("/selectEnterpriseInfo", {
      params: {
        enterpriseId: enterpriseId
      }
    });
    $nuxt.$store.commit("authen/setEnterpriseInfo", enterpriseInfo.data);// 保存油企信息
    
    console.log('222---查询油企信息data：',enterpriseInfo.data.url);

      // 无openid，先跳转获取openid
      console.log("333---openId有吗", $nuxt.$store.getters["authen/openId"]);

    // 如果不存在用户的openId，则说明是第一次进来，也就是新用户进来，则需要走微信认证授权
    if (!$nuxt.$store.getters["authen/openId"]) {
      console.log('444----没有openId，$nuxt.$store.getters["authen/openId"]-----------------')
      console.log("我要微信认证了",originUrl); 
      // 这里的originUrl 就是一开始进入页面的链接  比如从扫员工码进来的时的链接是:/246/fuel/remit/.stationId_321-stationName_test342-userId_742-utmSource_1
      
      // 获取appid
      $nuxt.$store.dispatch("authen/getAppId", enterpriseId).then((res) => {
        sessionStorage.setItem("enterpriseId", enterpriseId);
        $nuxt.$store.commit("authen/setEnterpriseId", enterpriseId);
        if (key === "remit") {
          // 扫员工码进入的情况
          console.log('-----remit------')
          if (enterpriseInfo.data["gzhAppSecret"] != undefined) {
            console.log('有密钥--老版本授权')
            // 老版本授权
            window.location.href =
              "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
              $nuxt.$store.getters["authen/appId"] +
              "&redirect_uri=" +
              settings.baseUrl +
              "remitAuth&response_type=code&scope=snsapi_base&state=" +
              originUrl +
              "#wechat_redirect";
              
          } else {
            // 新版本授权
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${$nuxt.$store.getters["authen/appId"]}&redirect_uri=${settings.baseUrl}remitAuth&response_type=code&scope=snsapi_base&state=${originUrl}&component_appid=wx61be193e633e76cf#wechat_redirect`;
          }
        } else {
          // 正常从会员中心页面进入
          console.log('-----my------')
          if (enterpriseInfo.data["gzhAppSecret"] != undefined) {
            // 老版本授权
            window.location.href =
              "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
              $nuxt.$store.getters["authen/appId"] +
              "&redirect_uri=" +
              settings.baseUrl +
              "authMy&response_type=code&scope=snsapi_base&state=" +
              originUrl +
              "#wechat_redirect";
          } else {
            // 新版本授权
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${$nuxt.$store.getters["authen/appId"]}&redirect_uri=${settings.baseUrl}authMy&response_type=code&scope=snsapi_base&state=${originUrl}&component_appid=wx61be193e633e76cf#wechat_redirect`;
          }
        }
      }).catch((error) => {
        alert(error+'失败')
      })
      return; 
    }

    //ToDo: 原来的代码  
    // const carUrlPro = await $nuxt.$axios.$get("/getCardUrl", {
    //   params: {
    //     openId: $nuxt.$store.getters["authen/openId"],
    //     enterpriseId: enterpriseId,
    //     outStr: originUrl,
    //   }
    // });

     // 获取分享者id:推荐有奖页面的链接会携带一个shareUserId的字段
     let shareUserId = Number(localStorage.getItem("shareUserId"));
     let carUrlPro
     if(shareUserId){
      carUrlPro = await $nuxt.$axios.$get("/getCardUrl", {
        params: {
          openId: $nuxt.$store.getters["authen/openId"],
          enterpriseId: enterpriseId,
          outStr: originUrl,
          shareUserId:shareUserId
        }
      });
     }else{
      console.log('1006--调用getCardUrl')
      carUrlPro = await $nuxt.$axios.$get("/getCardUrl", {
        params: {
          openId: $nuxt.$store.getters["authen/openId"],
          enterpriseId: enterpriseId,
          outStr: originUrl,
        }
      });
     }
    
    console.log('carUrlPro',carUrlPro);
    console.log('carUrlPro-data',carUrlPro.data)

    debugger
    // if (carUrlPro.retCode != 0) {
    //   throw new Error("加载跳转地址失败");
    // }
    if ([-4, -5, -9].includes(carUrlPro.retCode)) {
      Toast(`网络波动${carUrlPro.retCode}`);
      carUrlPro = await $nuxt.$axios.$get("/getCardUrl", {
        params: {
          openId: $nuxt.$store.getters["authen/openId"],
          enterpriseId: enterpriseId,
          outStr: originUrl
        }
      });
      Toast(`网络波动${carUrlPro.retCode}`);
      console.log("得到的跳转地址", carUrlPro);
      sessionStorage.setItem("enterpriseId", enterpriseId);
      if (!!carUrlPro.data.url) {
        // 有url 直接跳转
        window.location.href = carUrlPro.data.url;
      } else if (!carUrlPro.data.url && !carUrlPro.data.mobilePhone) {
        // 无url 无手机号
        throw new Error("跳转地址返回结果不正确");
      } else {
        const unionIdStr = !!carUrlPro.data.unionId
          ? "&unionid=" + carUrlPro.data.unionId
          : "";
        const originUrlStr = !!originUrl ? "&originurl=" + originUrl : "";

        if (key === "remit") {
          window.location.href =
            "/remitAuth?openid=" +
            $nuxt.$store.getters["authen/openId"] +
            "&phone=" +
            carUrlPro.data.mobilePhone +
            originUrlStr +
            unionIdStr;
        } else {
          window.location.href =
            "/authMy?openid=" +
            $nuxt.$store.getters["authen/openId"] +
            "&phone=" +
            carUrlPro.data.mobilePhone +
            originUrlStr +
            unionIdStr;
        }
      }
      return;
    }

    if (carUrlPro.retCode === -1) {
      Toast(`网络波动${carUrlPro.retCode}`);
      setTimeout(async () => {
        carUrlPro = await $nuxt.$axios.$get("/getCardUrl", {
          params: {
            openId: $nuxt.$store.getters["authen/openId"],
            enterpriseId: enterpriseId,
            outStr: originUrl
          }
        });
      }, 2000);
      Toast(`网络波动${carUrlPro.retCode}`);
      console.log("得到的跳转地址", carUrlPro);
      sessionStorage.setItem("enterpriseId", enterpriseId);
      if (!!carUrlPro.data.url) {
        // 有url 直接跳转
        window.location.href = carUrlPro.data.url;
      } else if (!carUrlPro.data.url && !carUrlPro.data.mobilePhone) {
        // 无url 无手机号
        throw new Error("跳转地址返回结果不正确");
      } else {
        const unionIdStr = !!carUrlPro.data.unionId
          ? "&unionid=" + carUrlPro.data.unionId
          : "";
        const originUrlStr = !!originUrl ? "&originurl=" + originUrl : "";

        if (key === "remit") {
          window.location.href =
            "/remitAuth?openid=" +
            $nuxt.$store.getters["authen/openId"] +
            "&phone=" +
            carUrlPro.data.mobilePhone +
            originUrlStr +
            unionIdStr;
        } else {
          window.location.href =
            "/authMy?openid=" +
            $nuxt.$store.getters["authen/openId"] +
            "&phone=" +
            carUrlPro.data.mobilePhone +
            originUrlStr +
            unionIdStr;
        }
      }
      return;
    }
    
    console.log("1007-得到的跳转地址", carUrlPro.data.url);
    sessionStorage.setItem("enterpriseId", enterpriseId);
    if (!!carUrlPro.data.url) {
      // 有url 直接跳转
      window.location.href = carUrlPro.data.url;
    } else if (!carUrlPro.data.url && !carUrlPro.data.mobilePhone) {
      // 无url 无手机号
      throw new Error("跳转地址返回结果不正确");
    } else {
      const unionIdStr = !!carUrlPro.data.unionId
        ? "&unionid=" + carUrlPro.data.unionId
        : "";
      const originUrlStr = !!originUrl ? "&originurl=" + originUrl : "";

      if (key === "remit") {
        window.location.href =
          "/remitAuth?openid=" +
          $nuxt.$store.getters["authen/openId"] +
          "&phone=" +
          carUrlPro.data.mobilePhone +
          originUrlStr +
          unionIdStr;
      } else {
        window.location.href =
          "/authMy?openid=" +
          $nuxt.$store.getters["authen/openId"] +
          "&phone=" +
          carUrlPro.data.mobilePhone +
          originUrlStr +
          unionIdStr;
      }
    }

    // $nuxt.$store.dispatch('authen/getAppId', enterpriseId).then(()=>{
    //   sessionStorage.setItem('enterpriseId', enterpriseId)
    //   window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + $nuxt.$store.getters["authen/appId"] + "&redirect_uri=" + settings.baseUrl + "authen&response_type=code&scope=snsapi_base&state=" + path + searchStr + "#wechat_redirect"
    // })
  } catch (e) {
    const msg = !!e.message ? e.message : e;
    alert(msg);
  }
};
